package com.rover.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.Common;
import com.grid.Page;
import com.rover.dao.BaseDao;
import com.rover.entity.system.Role;
import com.rover.entity.system.User;
import com.rover.entity.system.UserRole;
import com.utils.Encrypt;

@Service("userService")
@Transactional
public class UserService{
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao<User> userDao;
	
	@Autowired
	private BaseDao<UserRole> userRoleDao;
	
	@Autowired
	private BaseDao<Role> roleDao;
	
	@Transactional
	public User getUserByUserName(String userName){
		if(StringUtils.isNotBlank(userName)){
			List<User> users = userDao.find("from User u where u.loginName='" + userName + "'");
			if(null != users && users.size() != 0){
				return users.get(0);
			}
		}
		return null;
	}
	
	@Transactional(readOnly = true)
    public Page<User> query(Page<User> page,Map<String, Object> params, String hql){
		hql = "from User " + hql;
		String rolesName = "",rolesId = "";
		List<User> users = userDao.find(hql, params,page.getPageNo() , page.getPageSize());
		if(null != users && users.size() != 0){
			for(User user : users){
				rolesName = "";
				rolesId = "";
				List<UserRole> userRoles = userRoleDao
						.find("from UserRole u where u.tuser='" + user.getId()
								+ "'");
				for (UserRole ur : userRoles) {
					rolesName += ur.getTrole().getName() + ",";
					rolesId += ur.getTrole().getId() + ",";
				}
				//删除最后一个,
				if (rolesName.length() > 0) {
					rolesName = rolesName.substring(0, rolesName.length() - 1);
					rolesId = rolesId.substring(0, rolesId.length() - 1);
				}
				user.setRolesName(rolesName);
				user.setRolesId(rolesId);
				
				int status = user.getStatus();
				if(status == 1){
					user.setStatusList("启用");
				}else {
					user.setStatusList("禁用");
				}
			}
		}
		page.setResult(users);
		String totalHql = "select count(*) " + hql;
		page.setTotalCount(userDao.count(totalHql, params));
	    return page;
	}
	
	@Transactional(readOnly = true)
	public Boolean isAddNameRepeat(String name){
		List<User> users = userDao.find("from User u where u.loginName='" + name + "'");
		if(users.size() > 0){
			return Boolean.FALSE;
		}else {
			return Boolean.TRUE;
		}
	}
	
	@Transactional(readOnly = true)
	public Boolean isEditNameRepeat(String name,Long id){
		List<User> users = userDao.find("from User where loginName=? and id<>?",name,id);
		if(users.size() > 0){
			return Boolean.FALSE;
		}else {
			return Boolean.TRUE;
		}
	}
	
	/*
	 * 获取此用户的角色id
	 * @user  用户实体类
	 * */
	@SuppressWarnings("unchecked")
	@Transactional
	public List<Long> getUserRole(User user){
	Query q=	userRoleDao.getCurrentSession().createQuery("select ur.trole.id from UserRole ur where ur.tuser=:user");
		q.setEntity("user", user);
	  return q.list();
	}
	/*
	 * 获取此用户是否是管理员
	 * @user  用户实体类
	 * */
	@SuppressWarnings("unchecked")
	@Transactional
	public Boolean getIsAdmin(User user){
	Query q=	userRoleDao.getCurrentSession().createQuery("from Role where  id in (select ur.trole.id from UserRole ur where ur.tuser=:user)");
		q.setEntity("user", user);
		List<Role> li=q.list();
		Boolean isAdmin=false;
		for(Role r :li){
			if(r.getsAdmin()!=null && r.getsAdmin().equals("0")){
				isAdmin=true;
		        break;
			}
		}
	  return isAdmin;
	}
	/*
	*保存数据
	*/
	@Transactional
	public void save(User user){
		//添加的时候初始化密码
		if(user.getId()==null){
			user.setPassword(Encrypt.md5(Common.ADMIN_PASSWORD));
		}
		else{
			//更新的时候删除对应的角色
			 Map<String, Object> params=new HashMap<String, Object>();
			 params.put("user", user);
			 userRoleDao.executeHql("delete UserRole ur where ur.tuser=:user", params);
			//将更新的数据覆盖原用户数据
			 User u = userDao.find("from User where id=?",user.getId()).get(0);
			 u.setName(user.getName());
			 u.setLoginName(user.getLoginName());
			 u.setEmail(user.getEmail());
			 u.setStatus(user.getStatus());
			 u.setRolesId(user.getRolesId());
			 user = u;
		}
		userDao.saveOrUpdate(user);
		//保存角色
		String roleIds = user.getRolesId();
		if(StringUtils.isNotBlank(roleIds)){
			String[] strRole = roleIds.split(",");
			List<Role> liRole = new ArrayList<Role>();
			UserRole ur = null;
			for(String str :strRole){
				liRole=	roleDao.find("from Role where id=?",Long.valueOf(str));
				if(liRole.size()>0){
					ur=new UserRole();
					ur.setTrole(liRole.get(0));
					ur.setTuser(user);
					userRoleDao.save(ur);
				}
			}
		}
	}

	/*
	*保存用户启用/禁用数据
	*/
	@Transactional
	public void saveEnable(User user) {
		userDao.saveOrUpdate(user);
	}
	
	/*
	*删除用户
	*/
	@Transactional
	public void delete(Long id) {
		userDao.delete(User.class,id);
	}
	
	/*
	 * 初始化密码
	 * @id  要初始化的用户id
	 * */
	@Transactional
	public void initPassword(Long id) {
		User user = userDao.find("from User where id=?", id).get(0);
		user.setPassword(Encrypt.md5(Common.ADMIN_PASSWORD));
		userDao.saveOrUpdate(user);
	}
	
	/*
	 * 根据HQL查找对应user表中数据
	 * */
	@Transactional
	public List<User> findByHql(String hql) {
		return userDao.find(hql);
	}
	

	/*
	 * 修改密码
	 * */
	@Transactional
	public Map<String, Object> savePassword(Long id,String password,String newPwd,String newPwdTwo){
		Map<String, Object> map = new HashMap<String, Object>();
		String message = null;
		Boolean flag = Boolean.TRUE;
		List<User> users = userDao.find("from User where id=?",id);
		User user = users.get(0);
		if(!newPwd.equals(newPwdTwo)){
			message = "两次输入密码不符，请重新输入";
			flag = Boolean.FALSE;
		}else if(StringUtils.isNotBlank(password)){
			if(!Encrypt.md5(password).equals(user.getPassword())){
				message = "原密码输入错误，请重新输入";
				flag = Boolean.FALSE;
			}else {
				message = "密码修改成功";
				flag = Boolean.TRUE;
				user.setPassword(Encrypt.md5(newPwd));
				userDao.save(user);
			}
		}else {
			message = "原密码输入不能为空";
			flag = Boolean.FALSE;
		}
		map.put("success", flag);
		map.put("message", message);
		return map;
	}
	
	/*
	 * 根据Id寻找对应user
	 * */
	@Transactional
	public User getUserById(String id){
		List<User> users = userDao.find("from User where id=?",Long.parseLong(id));
		if(null != users && users.size() != 0){
			return users.get(0);
		}
		return null;
	}
	
}
